package jp.co.systemi.asp.workflow.peer;

import java.util.logging.Logger;

import jp.co.systemi.asp.workflow.data.Group;
import jp.co.systemi.asp.workflow.data.GroupMeta;
import jp.co.systemi.asp.workflow.data.User;
import jp.co.systemi.asp.workflow.data.UserGroup;
import jp.co.systemi.asp.workflow.data.UserGroupMeta;
import jp.co.systemi.asp.workflow.data.UserMeta;

import org.slim3.datastore.Datastore;

public class UserGroupPeer{
    @SuppressWarnings("unused")
    private static final Logger log = Logger.getLogger(UserGroupPeer.class
            .getName());

    public static UserGroup getManager(String loginId, String role) {
        UserGroupMeta ugm = UserGroupMeta.get();
        // まず所属グループを取得する
        UserGroup belong = Datastore.query(ugm).filter(
                ugm.loginId.equal(loginId), ugm.main.equal(true)).asSingle();
        if (belong == null) {
            return null;
        }
        GroupMeta gm = GroupMeta.get();
        UserMeta um = UserMeta.get();
        Group group = Datastore.query(gm).filter(
                gm.code.equal(belong.getGroupCode())).asSingle();
        if (group == null) {
            return null;
        }
        while (true) {
            // グループに該当役割のユーザを検索する
            UserGroup roleGroup = Datastore.query(ugm).filter(
                    ugm.groupCode.equal(group.getCode()), ugm.role.equal(role))
                    .asSingle();
            if (roleGroup != null) {
                // ユーザー名
                User user = Datastore.query(um).filter(um.loginId.equal(roleGroup.getLoginId())).asSingle();
                if(user != null){
                    roleGroup.setUserName(UserPeer.getName(user));
                }
                else {
                    return null;
                }
                //　グループ名
                group = Datastore.query(gm).filter(gm.code.equal(roleGroup.getGroupCode())).asSingle();
                if(group != null){
                    roleGroup.setGroupName(group.getName());
                }
                else {
                    return null;
                }
                return roleGroup;
            }
            // さかのぼって、親組織を検索する
            group = Datastore.query(gm).filter(
                    gm.code.equal(group.getParentGroup())).asSingle();
            if (group == null) {
                return null;
            }
        }
    }

}
